﻿using System.Web.Mvc;

namespace CodeContrib.Web.Mvc.Html
{
	public static class StylesheetExtensions
	{
		public static MvcHtmlString JQueryStylesheet(this HtmlHelper htmlHelper, string localUrl)
		{
			const string url = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css";

			return StylesheetCdn(htmlHelper, url, localUrl);
		}

		public static MvcHtmlString Stylesheet(this HtmlHelper htmlHelper, string url)
		{
			Guard.NotNullOrEmpty(url, "url");

			var stylesheet = new TagBuilder("link");
			stylesheet.Attributes["href"] = url.VerifyUrlProtocol();
			stylesheet.Attributes["rel"] = "stylesheet";
			stylesheet.Attributes["type"] = "text/css";

			return MvcHtmlString.Create(stylesheet.ToString(TagRenderMode.SelfClosing));
		}

		public static MvcHtmlString StylesheetCdn(this HtmlHelper htmlHelper, string cdnUrl, string localUrl)
		{
			var cdnStylesheet = Stylesheet(htmlHelper, cdnUrl);

			if (string.IsNullOrEmpty(localUrl))
			{
				return cdnStylesheet;
			}

			var localScript = new TagBuilder("script")
				                  {
					                  InnerHtml = string.Format("if (document.styleSheets) {{ var isLoaded = false; for (i = 0; i < document.styleSheets.length; i++) {{ if (document.styleSheets[i].href === '{0}') {{ isLoaded = true; break; }} }} if (!isLoaded) {{ document.write(unescape('%3Clink href=\"{1}\")\" rel=\"stylesheet\" type=\"text/css\" /%3E>')); }} }}", cdnUrl, localUrl)
				                  };
			localScript.Attributes["type"] = "text/javascript";

			return MvcHtmlString.Create(string.Concat(cdnStylesheet, localScript));
		}
	}
}